import 'dart:math';

import 'package:flutter/material.dart';

class TableWidget<T> extends StatelessWidget {
  final List<T> dataList;
  final Widget Function(BuildContext context, T data) builder;
  final int maxCountPerLine;
  final double horizontalSpace;
  final double verticalSpace;

  const TableWidget({
    Key? key,
    required this.dataList,
    this.maxCountPerLine = 3,
    this.horizontalSpace = 12,
    this.verticalSpace = 12,
    required this.builder,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (dataList.isEmpty) return Offstage();
    final len = dataList.length;
    int placeHolderCount = maxCountPerLine - len % maxCountPerLine;
    int rowCount = len ~/ maxCountPerLine + 1;

    List<TableRow> rows = [];

    for (int i = 0; i < rowCount; i++) {
      final startIndex = i * maxCountPerLine;
      final endIndex = min(maxCountPerLine * (i + 1), dataList.length);
      final subItems = dataList.sublist(startIndex, endIndex);
      final List<Widget> children = [];
      for (int j = 0; j < subItems.length; j++)
        children.add(
          Padding(
            padding: EdgeInsets.only(
              top: i != 0 ? verticalSpace : 0,
              right: j < maxCountPerLine - 1 ? horizontalSpace : 0,
            ),
            child: builder(context, subItems[j]),
          ),
        );
      if (placeHolderCount > 0 && i == rowCount - 1) {
        for (int i = 0; i < placeHolderCount; i++) {
          children.add(Offstage());
        }
      }
      rows.add(TableRow(children: children));
    }

    return Table(children: rows);
  }
}
